﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Shard.Contracts.UserService;
using Shard.Contracts.UserService.Dtos;
using UserService.Domain.Entities;
using UserService.Domain.Managers;
using UserService.Domain.Shared.Cache;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Caching;
using Volo.Abp.Domain.Repositories;

namespace UserService.Application;

/// <summary>
/// 用户应用服务实现
/// </summary>
public class UserAppService : ApplicationService, IUserAppService
{
    private readonly UserManager _userManager;
    private readonly IRepository<UserAggregateRoot, Guid> _userRepository;
    private readonly IDistributedCache<UserDto> _userCache;

    public UserAppService(
        UserManager userManager,
        IRepository<UserAggregateRoot, Guid> userRepository,
        IDistributedCache<UserDto> userCache)
    {
        _userManager = userManager;
        _userRepository = userRepository;
        _userCache = userCache;
    }

    /// <summary>
    /// 创建用户
    /// </summary>
    public async Task<UserDto> CreateAsync(CreateUserDto input)
    {
        // 调用领域服务创建用户
        var user = await _userManager.CreateAsync(
            input.UserName,
            input.NickName,
            input.Email,
            input.PhoneNumber,
            input.Password);

        // 对象映射转换为DTO
        return ObjectMapper.Map<UserAggregateRoot, UserDto>(user);
    }

    /// <summary>
    /// 获取用户信息（带缓存）
    /// </summary>
    public async Task<UserDto?> GetAsync(Guid id)
    {
        // 先从缓存获取用户信息
        return await _userCache.GetOrAddAsync(
            UserServiceCacheKeys.UserInfo(id),
            async () =>
            {
                var user = await _userRepository.GetAsync(id);
                return ObjectMapper.Map<UserAggregateRoot, UserDto>(user);
            },
            // 缓存30分钟
            () => new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30)
            }
        );
    }

    /// <summary>
    /// 分页获取用户列表
    /// </summary>
    public async Task<PagedResultDto<UserDto>> GetListAsync(PagedAndSortedResultRequestDto input)
    {
        // 获取分页数据
        var users = await _userRepository.GetPagedListAsync(
            input.SkipCount,
            input.MaxResultCount, input.Sorting);

        // 转换为DTO
        var userDtos = ObjectMapper.Map<List<UserAggregateRoot>, List<UserDto>>(users);

        return new PagedResultDto<UserDto>(users.Count, userDtos);
    }

}